<!-- 指南 -->
<template>
    <ContentWrap>
        <div class="flex justify-between">
            <div class="flex aic">
                <ElButton type="primary" :icon="Plus" @click="onAdd">
                    {{ t('新增课程') }}
                </ElButton>
            </div>
            <div class="">
                <ElInput v-model="state.searchData.jobValue" style="width: 266px;height: 32px;margin-right: 10px;"
                    placeholder="请输入课程名称" :prefix-icon="Search" />
                <ElInput v-model="state.searchData.keywords" style="width: 266px;height: 32px;margin-right: 10px;"
                    placeholder="请输入课程内容" :prefix-icon="Search" />
                <ElInput v-model="state.searchData.companyValue" style="width: 266px;height: 32px;margin-right: 10px;"
                    placeholder="请输入讲师姓名" :prefix-icon="Search" />
                <ElButton type="primary" :icon="Search" @click="onSearch">
                    {{ t('common.query') }}
                </ElButton>
                <ElButton :icon="Refresh" @click="onReset">
                    {{ t('common.reset') }}
                </ElButton>

            </div>
        </div>
        <div class="" style="margin-top: 25px;">
            <Table v-model:pageSize="pageSize" v-model:currentPage="currentPage" :columns="allSchemas.tableColumns"
                :data="dataList" :loading="loading" :pagination="{ total: total }" @register="tableRegister"
                :headerCellStyle="headerCellStyle" :rowStyle="rowStyle" />
        </div>
    </ContentWrap>
    <Dialog v-model="dialogVisible1" :title="state.dialogVisible1title">
        <el-form ref="ruleFormRef" :model="state.ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
            status-icon>
            <div class="flex jcsb">
                <el-form-item label="课程名称" prop="contentTitle">
                    <el-input v-model="state.ruleForm.contentTitle" placeholder="请输入课程名称" />
                </el-form-item>
                <el-form-item label="讲师姓名" prop="">
                    <el-input v-model="state.ruleForm.contentSource" placeholder="请输入讲师姓名" />
                </el-form-item>
            </div>
            <div class="flex jcsb">
                <el-form-item label="课程费用" prop="">
                    <el-input v-model="state.ruleForm.otherInfo.free" placeholder="请输入课程费用" />
                </el-form-item>
                <el-form-item label="课程时间" prop="">
                    <el-input v-model="state.ruleForm.otherInfo.date" placeholder="请输入课程时间" />
                </el-form-item>
            </div>
            <div class="flex jcsb">
                <el-form-item label="课程地点" prop="">
                    <el-input v-model="state.ruleForm.otherInfo.address" placeholder="请输入课程地点" />
                </el-form-item>
                <el-form-item label="课程类别" prop="">
                    <el-select v-model="state.ruleForm.contentType" class="m-2" clearable placeholder="请选择课程类别">
                        <el-option v-for="item in state.optionsType" :key="item.dictValue" :label="item.dictLabel"
                            :value="item.dictValue" />
                    </el-select>
                </el-form-item>
            </div>
            <el-form-item label="讲师介绍" prop="">
                <el-input v-model="state.ruleForm.otherInfo.detail" placeholder="请输入讲师介绍" :autosize="{ minRows: 2 }"
                    type="textarea" row="4" />
            </el-form-item>
            <el-form-item label="课程内容" prop="contentContents">
                <Editor height="350px" v-model="state.ruleForm.contentContents" placeholder="请输入课程内容" />
                <!-- <Editor /> -->
                <!-- <el-input v-model="state.ruleForm.trainingContents" placeholder="请输入课程内容" :autosize="{ minRows: 2}" type="textarea" row="4" /> -->
            </el-form-item>
            <el-form-item label="上传附件" prop="">
                <el-upload v-model:file-list="state.fileList" class="upload-demo" :action="state.uploadFile.actionUrl"
                    multiple :headers="state.uploadFile.headers" :on-preview="handlePreview" :on-remove="handleRemove"
                    :before-remove="beforeRemove" :limit="state.uploadFile.limit" :on-exceed="handleExceed">
                    <el-button type="primary">上传附件</el-button>
                    <template #tip>
                        <div class="el-upload__tip">
                            {{ state.uploadFile.tip }}
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
            <!-- <el-form-item label="录用名单" prop="">
                <el-table :data="state.ruleForm.tableData" style="width: 100%" :headerCellStyle="headerCellStyle" :rowStyle="rowStyle">
                    <el-table-column prop="姓名" label="姓名" width="180" />
                    <el-table-column prop="岗位名称" label="岗位名称" width="180" />
                    <el-table-column prop="身份证号" label="身份证号" />
                </el-table>
            </el-form-item> -->
            <el-form-item>
                <div class="flex jcfe w-[100%]">
                    <el-button type="primary" v-loading="loadingAdd" @click="submitForm(ruleFormRef)">保存</el-button>
                    <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                </div>
            </el-form-item>
        </el-form>
    </Dialog>
</template>
    
<script setup lang="tsx">
import { getTypeListApi } from "@/api/common/index"
import { getTreeLists } from "@/api/column/index"
import { Editor } from "@/components/Editor/index"
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { Dialog } from '@/components/Dialog'
import { useEmitt } from '@/hooks/event/useEmitt'
import { ElButton, ElInput, ElMessage, ElMessageBox, ElSwitch } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { ContentWrap } from '@/components/ContentWrap'
import { ref, reactive, unref } from "vue"
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { formatToDateTime } from "@/utils/dateUtil"
import type { FormInstance, FormRules } from 'element-plus'
import { getBaseApi, getBaselistApi, addBaseApi, putBaseApi, addsDeteleBaseApi, addsBaseApi, deteleBaseApi, getDetailApi } from "@/api/setting/index";
import { getTalentTrainingListApi, addTalentTrainingApi, editTalentTrainingApi, deleteTalentTrainingApi } from "@/api/setting/index"
import { useRouter } from 'vue-router'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { useAppStoreWithOut } from '@/store/modules/app'
import { useStorage } from '@/hooks/web/useStorage'
const { getStorage } = useStorage()
const appStore = useAppStoreWithOut()
const userInfo = getStorage(appStore.getUserInfo)
const { push } = useRouter()
const props = { multiple: true }
interface RuleForm {
    contentType: string
    contentContents: string
    picOssIds: string
    bigPicOssIds: string
    contentTitle: string
}
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<RuleForm>>({
    picOssIds: [{ required: true, message: '必填项', trigger: 'blur', },],
    contentTitle: [{ required: true, message: '必填项', trigger: 'blur', },],
    contentType: [{ required: true, message: '必选项', trigger: 'change' },],
    contentContents: [{ required: true, message: '必填项', trigger: 'blur' },],
    bigPicOssIds: [{ required: true, message: '必填项', trigger: 'blur', },],
})
function urlFun(data) {
    let arrays = [] as any
    data.forEach(element => {
        let obj = {
            response: {
                data: {
                    fileName: element.originalName,
                    ossId: element.ossId,
                    url: element.url
                }
            },
            name: element.originalName,
            url: element.url
        }
        arrays.push(obj)
    });
    console.log(arrays);
    return arrays


}
function fileUrls(data) {
    let array = ""
    for (let index = 0; index < data.length; index++) {
        if (index == 0) {
            array = data[index].response.data.ossId
        } else {
            array = array + "," + data[index].response.data.ossId
        }
    }
    return array
}
const loadingAdd = ref(false)
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            console.log(state.fileList);
            state.ruleForm.annexOssIds = fileUrls(state.fileList)
            if (state.dialogVisible1title == '新增课程') {
                let obj = {
                    contentTitle: state.ruleForm.contentTitle,
                    contentContents: state.ruleForm.contentContents,
                    baseTitle: state.baseTitle,
                    // picOssIds: state.ruleForm.picOssIds,
                    annexOssIds: state.ruleForm.annexOssIds,
                    contentSource: state.ruleForm.contentSource,
                    // orderNumber: state.ruleForm.orderNumber,
                    baseType: state.baseType,
                    contentType: state.ruleForm.contentType,
                    otherInfo: JSON.stringify(state.ruleForm.otherInfo)

                }
                addBaseApi(obj).then((res: any) => {
                    ElMessage({
                        type: 'success',
                        message: `${res.msg}`,
                    })
                    formEl.resetFields()
                    getList()
                    dialogVisible1.value = false
                    loadingAdd.value = false
                }).catch((res: any) => {
                    ElMessage({
                        type: 'error',
                        message: `${res.msg}`,
                    })
                    loadingAdd.value = false
                })
            } else {
                let obj = {
                    id: state.ruleForm.id,
                    contentTitle: state.ruleForm.contentTitle,
                    contentContents: state.ruleForm.contentContents,
                    baseTitle: state.baseTitle,
                    // picOssIds: state.ruleForm.picOssIds,
                    annexOssIds: state.ruleForm.annexOssIds,
                    contentSource: state.ruleForm.contentSource,
                    // orderNumber: state.ruleForm.orderNumber,
                    baseType: state.baseType,
                    contentType: state.ruleForm.contentType,
                    otherInfo: JSON.stringify(state.ruleForm.otherInfo)
                }
                putBaseApi(obj).then((res: any) => {
                    ElMessage({
                        type: 'success',
                        message: `${res.msg}`,
                    })
                    formEl.resetFields()
                    getList()
                    dialogVisible1.value = false
                    loadingAdd.value = false
                }).catch((res: any) => {
                    ElMessage({
                        type: 'error',
                        message: `${res.msg}`,
                    })
                    loadingAdd.value = false
                })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
const resetForm = (formEl: FormInstance | undefined) => {
    dialogVisible1.value = false
    if (!formEl) return
    formEl.resetFields()
}
const { t } = useI18n()
const dialogVisible1 = ref(false)//定义职位详情弹框
const state = reactive({
    optionsType: [] as any,
    baseTitle: "Train",
    baseType: "",
    searchData: {
        companyValue: "",
        jobValue: "",
        keywords: ""
    },//搜索参数
    fileList: [] as any,
    react: true,//分页刷新
    dialogVisible1title: "新增办事指南",
    ruleForm: {
        tableData: [
            {
                date: '2016-05-03',
                name: 'Tom',
                address: 'No. 189, Grove St, Los Angeles',
            }

        ]
    } as any,
    uploadFile: {
        tip: "注意:单个文件大小不超过10M，最多上传5个，支持Excel格式",
        urls: [],
        ossIds: "",
        limit: 10,
        actionUrl: "/api/resource/oss/upload",
        headers: {
            "Authorization": `Bearer ${userInfo ? userInfo.access_token : ""}`,
            "clientid": userInfo ? userInfo.client_id : "e5cd7e4891bf95d1d19206ce24a7b32e"
        }
    },
})
// 表格基本信息
const crudSchemas = reactive<CrudSchema[]>([
    {
        field: 'contentTitle',
        label: t('课程名称'),
    },
    {
        field: 'contentSource',
        label: t('讲师'),
    },

    {
        field: 'contentContents',
        label: t('课程内容'),
        search: {
            hidden: true
        }
    },
    {
        field: 'contentTypes',
        label: t('课程类别'),
    },
    {
        field: 'viewNumber',
        label: t('浏览量'),
        search: {
            hidden: true
        }
    },
    {
        field: 'createTime',
        label: t('发布时间'),
        search: {
            hidden: true
        }
    },
    {
        field: 'isTop',
        label: t('是否置顶'),
        search: {
            hidden: true
        },
        table: {
            slots: {
                default: (data: any) => {
                    return (
                        <>
                            <div ><ElSwitch style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" active-value="0" inactive-value="1" v-model={data[0].row.isTop} before-change={() => switchClick(data[0].row)} /></div>
                        </>
                    )
                }
            }
        }
    },
    {
        field: 'status',
        label: t('是否展示'),
        search: {
            hidden: true
        },
        table: {
            slots: {
                default: (data: any) => {
                    return (
                        <>
                            <div ><ElSwitch style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" active-value="0" inactive-value="1" v-model={data[0].row.status} before-change={() => switchClicks(data[0].row)} /></div>
                        </>
                    )
                }
            }
        }
    },
    {
        field: 'action',
        width: '260px',
        label: t('tableDemo.action'),
        search: {
            hidden: true
        },
        form: {
            hidden: true
        },
        detail: {
            hidden: true
        },
        table: {
            slots: {
                default: (data: any) => {
                    return (
                        <>
                            <ElButton link type="primary" onClick={() => action(data[0].row)}>
                                {t('编辑')}
                            </ElButton>
                            {/* <ElButton link type="primary" onClick={() => receat(data[0].row)}>
                                {t('查看')}
                            </ElButton> */}
                            <ElButton link type="danger" onClick={() => delData(data[0].row)}>
                                {t('删除')}
                            </ElButton>

                        </>
                    )
                }
            }
        }
    }
])
const contentTypeFun = (res) => {
    let string = ""
    state.optionsType.forEach(element => {
        if (element.dictValue == res) {
            string = element.dictLabel
        }
    });
    return string
}
const { tableRegister, tableState, tableMethods } = useTable({
    fetchDataApi: async () => {
        const { currentPage, pageSize } = tableState
        const res: any = await getBaselistApi({
            pageNum: state.react ? 1 : unref(currentPage),
            pageSize: unref(pageSize),
            contentTitle: state.searchData.jobValue,
            contentContents: state.searchData.keywords,
            contentSource: state.searchData.companyValue,
            baseTitle: state.baseTitle,
            isAsc:"desc",
            orderByColumn:"createTime"
        })
        res.rows.forEach(element => {
            element.status = element.status.toString()
            element.isTop = element.isTop.toString()
            element.contentTypes = contentTypeFun(element.contentType)
        })
        console.log(res);
        state.react = false
        return {
            list: res.rows,
            total: res.total
        }
    }
})
// 表格头部信息
const headerCellStyle: any = {
    "background": "#F2F6FC",
    "height": "48px"
}
// 
const rowStyle: any = {
    "height": "48px"
}
const switchClick = (rows) => {
    let strings = rows.isTop == 1 ? "确认置顶？" : "取消置顶？"
    ElMessageBox.confirm(
        `${strings}`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            let params = {
                id: rows.id,
                isTop: rows.isTop == 0 ? "1" : "0",
                baseTitle: rows.baseTitle,
            }
            putBaseApi(params).then((res: any) => {
                ElMessage({
                    type: 'success',
                    message: `${res.msg}`,
                })
                getList()
            }).catch((res: any) => {
                ElMessage({
                    type: 'error',
                    message: `${res.msg}`,
                })
            })

        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消操作',
            })
        })
}
const switchClicks = (rows) => {
    let strings = rows.status == 1 ? "确定展示？" : "取消展示？"
    ElMessageBox.confirm(
        `${strings}`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            let params = {
                id: rows.id,
                status: rows.status == 0 ? "1" : "0",
                baseTitle: rows.baseTitle,
            }
            putBaseApi(params).then((res: any) => {
                ElMessage({
                    type: 'success',
                    message: `${res.msg}`,
                })
                getList()
            }).catch((res: any) => {
                ElMessage({
                    type: 'error',
                    message: `${res.msg}`,
                })
            })

        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消操作',
            })
        })
}
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods
// getList()
useEmitt({
    name: 'getList',
    callback: (type: string) => {
        if (type === 'add') {
            currentPage.value = 1
        }
        getList()
    }
})
const { allSchemas } = useCrudSchemas(crudSchemas)
// 详情
const detailClick = (data: any) => {
    push(`/Dictionary/Dictionary_Detail-index/${0}`)
}
// 新增
const onAdd = () => {
    state.ruleForm = {
        otherInfo:{}
    }
    state.fileList = []
    dialogVisible1.value = true
    state.dialogVisible1title = t('新增课程')
}
const action = (row: any) => {
    console.log("详情", row);
    dialogVisible1.value = true
    state.ruleForm = row
    state.ruleForm.otherInfo = JSON.parse(state.ruleForm.otherInfo)
    state.fileList = urlFun(row.annexFiles)
    state.dialogVisible1title = t('编辑课程')
}
const delData = (row: any) => {
    ElMessageBox.confirm('确认删除该课程？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // inputPattern:,
        draggable: true,
        type: 'warning',
    }).then(() => {
        deteleBaseApi(row.id).then((res: any) => {
            getList()
            ElMessage({
                type: 'success',
                message: `${res.msg}`,
            })
        }).catch((res: any) => {
            ElMessage({
                type: 'error',
                message: `${res.msg}`,
            })
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '取消操作',
        })
    })
}
const getTreeListApi = async () => {
    let params = {}
    getTreeLists(params).then(res => {
        console.log("详情：", res);
        res.data.forEach(element => {
            traverseTree(element)
        });
        console.log(state.baseType);
        getList()

    })
}
function traverseTree(node) {
    if (node.data.baseTitle == state.baseTitle) {
        state.baseType = node.data.baseType
    }
    if (node.children && node.children.length > 0) {
        for (let child of node.children) {
            traverseTree(child); // 递归遍历子节点  
        }
    }
}
getTreeListApi()
// 查询
const onSearch = () => {
    console.log("查询");
    state.react = true
    getList()
}
// 重置
const onReset = () => {
    console.log("重置");
    state.searchData.companyValue = ""
    state.searchData.keywords = ""
    state.searchData.jobValue = ""
    state.react = true
    getList()
}
// ============================
const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
    console.log(file, uploadFiles)

}

const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
    console.log(uploadFile)

}

const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
    ElMessage.warning(
        `最大上传${state.uploadFile.limit}个文件！`
    )
}

const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
    return ElMessageBox.confirm(
        `是否移除该附件?`
    ).then(
        () => true,
        () => false
    )
}
// api区域---------------------------------------------------------------------------
// 字典
const getTypeListApi_ = (params) => {
    getTypeListApi(params).then((res: any) => {
        console.log("字典", res);
        state.optionsType = res.data
    })
}
getTypeListApi_("class_type")

</script>
    
<style lang="less" scoped></style>